package com.timing.feedback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.timing.feedback.entity.Opinions;
import com.timing.feedback.entity.UserPO;
import com.timing.feedback.entity.UserOpinionsCount;
import com.timing.feedback.mapper.OpinionsMapper;
import com.timing.feedback.mapper.UserOpinionsCountMapper;
import com.timing.feedback.service.OpinionsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.timing.feedback.vo.ResultVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cwh
 * @since 2021-05-27
 */
@Service
public class OpinionsServiceImpl extends ServiceImpl<OpinionsMapper, Opinions> implements OpinionsService {

    @Resource
    private OpinionsMapper opinionsMapper;

    @Resource
    private UserOpinionsCountMapper userOpinionsCountMapper;

    @Override
    public ResultVO saveOpinionsAndCount(Opinions opinions) {
        //通过上下文获取id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object details = authentication.getDetails();
        if (details instanceof UserPO){
            opinions.setUserId(((UserPO) details).getId());
            //将创建时间和修改时间设为null,
            opinions.setCreateTime(null);
            opinions.setUpdateTime(null);
        }
        //插入数据
        int opinionInsert = opinionsMapper.insert(opinions);

        //判断是否插入成功,若插入成功，更新userOpinionsCount表
        if (opinionInsert == 1){
            //查询此用户是否有记录，用userId查询
            LambdaQueryWrapper<UserOpinionsCount> wrapper = new QueryWrapper<UserOpinionsCount>().lambda();
            UserOpinionsCount userOpinionsCount =
                userOpinionsCountMapper.selectOne(wrapper.eq(UserOpinionsCount::getUserId,opinions.getId()));
            if (userOpinionsCount == null){
                //记录为空插入第一条记录
                int insertCount = userOpinionsCountMapper.insert(new UserOpinionsCount(opinions.getId(), 1,
                    new Date()));
                //insertCount ==1说明插入成功
                return insertCount == 1 ? ResultVO.ok() : ResultVO.error();
            }
            //
            int insertCount = userOpinionsCountMapper.addUserCount(opinions.getId());
            //insertCount ==1说明修改成功
            return insertCount == 1 ? ResultVO.ok() : ResultVO.error();
        }
        return ResultVO.error();
    }


}
